package com.ruoyi.common.utils.html;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * HTML过滤器，用于去除XSS漏洞隐患。
 *
 * @author ruoyi
 */
public final class HTMLFilter {
    /**
     * 正则表达式标志，代表PHP中的/si修饰符
     * /s 代表DOTALL模式，使.匹配包括换行符在内的所有字符
     * /i 代表CASE_INSENSITIVE模式，不区分大小写匹配
     **/
    private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;

    /** 匹配HTML注释 <!--(.*?)--> */
    private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL);

    /** 匹配注释内容 ^!--(.*)--$ */
    private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI);

    /** 匹配HTML标签 <(.*?)> */
    private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);

    /** 匹配结束标签 /^/([a-z0-9]+) */
    private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);

    /** 匹配开始标签 /^([a-z0-9]+)(.*?)(/?)$ */
    private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);

    /** 匹配带引号的属性 ([a-z0-9]+)=([\"'])(.*?)\2 */
    private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);

    /** 匹配不带引号的属性 ([a-z0-9]+)(=)([^\"\s']+) */
    private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);

    /** 匹配协议 ^([^:]+): */
    private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);

    /** 匹配十进制HTML实体 &#(\d+);? */
    private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?");

    /** 匹配十六进制HTML实体 &#x([0-9a-f]+);? */
    private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");

    /** 匹配URL编码 %([0-9a-f]{2});? */
    private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");

    /** 匹配有效的HTML实体 &([^&;]*)(?=(;|&|$)) */
    private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");

    /** 匹配引号 ^(>|^)([^<]+?)(<|$) */
    private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);

    /** 匹配结束箭头 ^> */
    private static final Pattern P_END_ARROW = Pattern.compile("^>");

    /** 匹配标签体到结束 <([^>]*?)(?=<|$) */
    private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");

    /** 匹配XML内容 (^|>)([^<]*?)(?=>) */
    private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");

    /** 匹配孤立的左箭头 <([^>]*?)(?=<|$) */
    private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");

    /** 匹配孤立的右箭头 (^|>)([^<]*?)(?=>) */
    private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");

    /** 匹配&符号 & */
    private static final Pattern P_AMP = Pattern.compile("&");

    /** 匹配双引号 " */
    private static final Pattern P_QUOTE = Pattern.compile("\"");

    /** 匹配左尖括号 < */
    private static final Pattern P_LEFT_ARROW = Pattern.compile("<");

    /** 匹配右尖括号 > */
    private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");

    /** 匹配左右尖括号 <> */
    private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");

    // @xxx could grow large... maybe use sesat's ReferenceMap
    // @xxx 可能会变得很大...也许可以使用sesat的ReferenceMap
    private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();
    private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();

    /**
     * 允许的HTML元素集合，以及每个元素允许的属性
     **/
    private final Map<String, List<String>> vAllowed;

    /**
     * 每个(允许的)HTML元素的开放标签计数
     **/
    private final Map<String, Integer> vTagCounts = new HashMap<>();

    /**
     * 必须始终自闭合的HTML元素(例如"<img />")
     **/
    private final String[] vSelfClosingTags;

    /**
     * 必须始终具有独立开闭标签的HTML元素(例如"<b></b>")
     **/
    private final String[] vNeedClosingTags;

    /**
     * 不允许的HTML元素集合
     **/
    private final String[] vDisallowed;

    /**
     * 应检查有效协议的属性
     **/
    private final String[] vProtocolAtts;

    /**
     * 允许的协议
     **/
    private final String[] vAllowedProtocols;

    /**
     * tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />")
     * 如果不包含内容应该被移除的标签(例如"<b></b>"或"<b />")
     **/
    private final String[] vRemoveBlanks;

    /**
     * entities allowed within html markup
     * HTML标记中允许的实体
     **/
    private final String[] vAllowedEntities;

    /**
     * flag determining whether comments are allowed in input String.
     * 标志，确定输入字符串中是否允许注释
     */
    private final boolean stripComment;
    private final boolean encodeQuotes;

    /**
     * flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. "<b text </b>"
     * becomes "<b> text </b>"). If set to false, unbalanced angle brackets will be html escaped.
     * 标志，确定当遇到"不平衡"的尖括号时是否尝试构建标签
     * (例如"<b text </b>"变成"<b> text </b>")。
     * 如果设置为false，不平衡的尖括号将被HTML转义。
     */
    private final boolean alwaysMakeTags;

    /**
     * 默认构造函数，初始化默认的HTML过滤规则
     */
    public HTMLFilter() {
        vAllowed = new HashMap<>();

        // 配置允许的<a>标签属性
        final ArrayList<String> a_atts = new ArrayList<>();
        a_atts.add("href");    // 超链接地址
        a_atts.add("target");  // 打开方式
        vAllowed.put("a", a_atts);

        // 配置允许的<img>标签属性
        final ArrayList<String> img_atts = new ArrayList<>();
        img_atts.add("src");    // 图片源地址
        img_atts.add("width");  // 宽度
        img_atts.add("height"); // 高度
        img_atts.add("alt");    // 替代文本
        vAllowed.put("img", img_atts);

        // 配置不需要属性的标签
        final ArrayList<String> no_atts = new ArrayList<>();
        vAllowed.put("b", no_atts);      // 粗体标签
        vAllowed.put("strong", no_atts); // 强调标签
        vAllowed.put("i", no_atts);      // 斜体标签
        vAllowed.put("em", no_atts);     // 强调标签

        // 设置自闭合标签
        vSelfClosingTags = new String[]{"img"};

        // 设置需要闭合标签的元素
        vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};

        // 设置不允许的标签（空表示都允许，除非在vAllowed中明确列出）
        vDisallowed = new String[]{};

        // 设置允许的协议（不包括ftp）
        vAllowedProtocols = new String[]{"http", "mailto", "https"};

        // 设置需要检查协议的属性
        vProtocolAtts = new String[]{"src", "href"};

        // 设置需要移除的空白标签
        vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};

        // 设置允许的HTML实体
        vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};

        // 设置是否移除注释（true表示移除）
        stripComment = true;

        // 设置是否编码引号
        encodeQuotes = true;

        // 设置是否总是尝试构建标签（false表示对不平衡括号进行转义）
        alwaysMakeTags = false;
    }

    /**
     * Map-parameter configurable constructor.
     * 映射参数可配置构造函数
     *
     * @param conf map containing configuration. keys match field names.
     *             包含配置的映射。键与字段名匹配。
     */
    @SuppressWarnings("unchecked")
    public HTMLFilter(final Map<String, Object> conf) {

        assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
        assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
        assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
        assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
        assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
        assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
        assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
        assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";

        vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed"));
        vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
        vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
        vDisallowed = (String[]) conf.get("vDisallowed");
        vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
        vProtocolAtts = (String[]) conf.get("vProtocolAtts");
        vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
        vAllowedEntities = (String[]) conf.get("vAllowedEntities");
        stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;
        encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;
        alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
    }

    /**
     * 重置标签计数器
     */
    private void reset() {
        vTagCounts.clear();
    }

    // ---------------------------------------------------------------
    // my versions of some PHP library functions
    // 一些PHP库函数的我的版本
    /**
     * 将十进制数转换为对应的字符
     *
     * @param decimal 十进制数值
     * @return 对应的字符
     */
    public static String chr(final int decimal) {
        return String.valueOf((char) decimal);
    }

    /**
     * 将特殊HTML字符转换为HTML实体
     *
     * @param s 输入字符串
     * @return 转换后的字符串
     */
    public static String htmlSpecialChars(final String s) {
        String result = s;
        result = regexReplace(P_AMP, "&amp;", result);        // & 转换为 &amp;
        result = regexReplace(P_QUOTE, "&quot;", result);     // " 转换为 &quot;
        result = regexReplace(P_LEFT_ARROW, "&lt;", result);  // < 转换为 &lt;
        result = regexReplace(P_RIGHT_ARROW, "&gt;", result); // > 转换为 &gt;
        return result;
    }

    // ---------------------------------------------------------------

    /**
     * given a user submitted input String, filter out any invalid or restricted html.
     * 给定用户提交的输入字符串，过滤掉任何无效或受限制的HTML。
     *
     * @param input text (i.e. submitted by a user) than may contain html
     *              文本(即由用户提交)可能包含HTML
     * @return "clean" version of input, with only valid, whitelisted html elements allowed
     *         输入的"干净"版本，只允许有效的白名单HTML元素
     */
    public String filter(final String input) {
        reset();
        String s = input;

        s = escapeComments(s);      // 转义注释

        s = balanceHTML(s);         // 平衡HTML标签

        s = checkTags(s);           // 检查标签

        s = processRemoveBlanks(s); // 处理空白标签

        // s = validateEntities(s);

        return s;
    }

    /**
     * 获取是否总是尝试构建标签的设置
     *
     * @return alwaysMakeTags标志的值
     */
    public boolean isAlwaysMakeTags() {
        return alwaysMakeTags;
    }

    /**
     * 获取是否移除注释的设置
     *
     * @return stripComment标志的值
     */
    public boolean isStripComments() {
        return stripComment;
    }

    /**
     * 转义注释中的内容
     *
     * @param s 输入字符串
     * @return 处理后的字符串
     */
    private String escapeComments(final String s) {
        final Matcher m = P_COMMENTS.matcher(s);
        final StringBuffer buf = new StringBuffer();
        if (m.find()) {
            final String match = m.group(1); // (.*?)
            m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
        }
        m.appendTail(buf);

        return buf.toString();
    }

    /**
     * 平衡HTML标签
     *
     * @param s 输入字符串
     * @return 处理后的字符串
     */
    private String balanceHTML(String s) {
        if (alwaysMakeTags) {
            // 尝试构建HTML
            s = regexReplace(P_END_ARROW, "", s);
            // 不追加结束标签
            s = regexReplace(P_BODY_TO_END, "<$1>", s);
            s = regexReplace(P_XML_CONTENT, "$1<$2", s);

        } else {
            // 转义孤立的括号
            s = regexReplace(P_STRAY_LEFT_ARROW, "&lt;$1", s);
            s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2&gt;<", s);

            // 最后一个正则表达式会导致'<>'实体出现
            // (我们需要做一个前瞻断言，以便最后一个括号可以在正则表达式的下一次传递中使用)
            s = regexReplace(P_BOTH_ARROWS, "", s);
        }

        return s;
    }

    /**
     * 检查并处理HTML标签
     *
     * @param s 输入字符串
     * @return 处理后的字符串
     */
    private String checkTags(String s) {
        Matcher m = P_TAGS.matcher(s);

        final StringBuffer buf = new StringBuffer();
        while (m.find()) {
            String replaceStr = m.group(1);
            replaceStr = processTag(replaceStr);
            m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
        }
        m.appendTail(buf);

        // 这些在processTag中被统计
        // (记住在后续调用filter方法之前要重置)
        final StringBuilder sBuilder = new StringBuilder(buf.toString());
        for (String key : vTagCounts.keySet()) {
            for (int ii = 0; ii < vTagCounts.get(key); ii++) {
                sBuilder.append("</").append(key).append(">");
            }
        }
        s = sBuilder.toString();

        return s;
    }

    /**
     * 处理空白标签的移除
     *
     * @param s 输入字符串
     * @return 处理后的字符串
     */
    private String processRemoveBlanks(final String s) {
        String result = s;
        for (String tag : vRemoveBlanks) {
            if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
                P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
            }
            result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
            if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) {
                P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
            }
            result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
        }

        return result;
    }

    /**
     * 使用正则表达式替换字符串
     *
     * @param regex_pattern 正则表达式模式
     * @param replacement 替换字符串
     * @param s 输入字符串
     * @return 替换后的字符串
     */
    private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
        Matcher m = regex_pattern.matcher(s);
        return m.replaceAll(replacement);
    }

    /**
     * 处理单个HTML标签
     *
     * @param s 标签字符串
     * @return 处理后的标签字符串
     */
    private String processTag(final String s) {
        // 处理结束标签
        Matcher m = P_END_TAG.matcher(s);
        if (m.find()) {
            final String name = m.group(1).toLowerCase();
            if (allowed(name)) {
                if (!inArray(name, vSelfClosingTags)) {
                    if (vTagCounts.containsKey(name)) {
                        vTagCounts.put(name, vTagCounts.get(name) - 1);
                        return "</" + name + ">";
                    }
                }
            }
        }

        // 处理开始标签
        m = P_START_TAG.matcher(s);
        if (m.find()) {
            final String name = m.group(1).toLowerCase();
            final String body = m.group(2);
            String ending = m.group(3);

            // debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
            if (allowed(name)) {
                final StringBuilder params = new StringBuilder();

                final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
                final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
                final List<String> paramNames = new ArrayList<>();
                final List<String> paramValues = new ArrayList<>();
                while (m2.find()) {
                    paramNames.add(m2.group(1)); // ([a-z0-9]+)
                    paramValues.add(m2.group(3)); // (.*?)
                }
                while (m3.find()) {
                    paramNames.add(m3.group(1)); // ([a-z0-9]+)
                    paramValues.add(m3.group(3)); // ([^\"\\s']+)
                }

                String paramName, paramValue;
                for (int ii = 0; ii < paramNames.size(); ii++) {
                    paramName = paramNames.get(ii).toLowerCase();
                    paramValue = paramValues.get(ii);

                    // debug( "paramName='" + paramName + "'" );
                    // debug( "paramValue='" + paramValue + "'" );
                    // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );

                    if (allowedAttribute(name, paramName)) {
                        if (inArray(paramName, vProtocolAtts)) {
                            paramValue = processParamProtocol(paramValue);
                        }
                        params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\\\"");
                    }
                }

                if (inArray(name, vSelfClosingTags)) {
                    ending = " /";
                }

                if (inArray(name, vNeedClosingTags)) {
                    ending = "";
                }

                if (ending == null || ending.length() < 1) {
                    if (vTagCounts.containsKey(name)) {
                        vTagCounts.put(name, vTagCounts.get(name) + 1);
                    } else {
                        vTagCounts.put(name, 1);
                    }
                } else {
                    ending = " /";
                }
                return "<" + name + params + ending + ">";
            } else {
                return "";
            }
        }

        // 处理注释
        m = P_COMMENT.matcher(s);
        if (!stripComment && m.find()) {
            return "<" + m.group() + ">";
        }

        return "";
    }

    /**
     * 处理参数协议验证
     *
     * @param s 输入字符串
     * @return 处理后的字符串
     */
    private String processParamProtocol(String s) {
        s = decodeEntities(s);
        final Matcher m = P_PROTOCOL.matcher(s);
        if (m.find()) {
            final String protocol = m.group(1);
            if (!inArray(protocol, vAllowedProtocols)) {
                // 错误的协议，转换为本地锚链接
                s = "#" + s.substring(protocol.length() + 1);
                if (s.startsWith("#//")) {
                    s = "#" + s.substring(3);
                }
            }
        }

        return s;
    }

    /**
     * 解码HTML实体
     *
     * @param s 输入字符串
     * @return 解码后的字符串
     */
    private String decodeEntities(String s) {
        StringBuffer buf = new StringBuffer();

        Matcher m = P_ENTITY.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.decode(match).intValue();
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();

        buf = new StringBuffer();
        m = P_ENTITY_UNICODE.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.valueOf(match, 16).intValue();
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();

        buf = new StringBuffer();
        m = P_ENCODE.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.valueOf(match, 16).intValue();
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();

        s = validateEntities(s);
        return s;
    }

    /**
     * 验证HTML实体
     *
     * @param s 输入字符串
     * @return 验证后的字符串
     */
    private String validateEntities(final String s) {
        StringBuffer buf = new StringBuffer();

        // 验证整个字符串中的实体
        Matcher m = P_VALID_ENTITIES.matcher(s);
        while (m.find()) {
            final String one = m.group(1); // ([^&;]*)
            final String two = m.group(2); // (?=(;|&|$))
            m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
        }
        m.appendTail(buf);

        return encodeQuotes(buf.toString());
    }

    /**
     * 编码引号
     *
     * @param s 输入字符串
     * @return 编码后的字符串
     */
    private String encodeQuotes(final String s) {
        if (encodeQuotes) {
            StringBuffer buf = new StringBuffer();
            Matcher m = P_VALID_QUOTES.matcher(s);
            while (m.find()) {
                final String one = m.group(1); // (>|^)
                final String two = m.group(2); // ([^<]+?)
                final String three = m.group(3); // (<|$)
                // 不替换双引号为&quot;，防止json格式无效 regexReplace(P_QUOTE, "&quot;", two)
                m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
            }
            m.appendTail(buf);
            return buf.toString();
        } else {
            return s;
        }
    }

    /**
     * 检查实体是否有效
     *
     * @param preamble 实体前缀
     * @param term 实体后缀
     * @return 处理后的实体字符串
     */
    private String checkEntity(final String preamble, final String term) {

        return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble;
    }

    /**
     * 检查实体是否在允许列表中
     *
     * @param entity 实体名称
     * @return 如果实体被允许返回true，否则返回false
     */
    private boolean isValidEntity(final String entity) {
        return inArray(entity, vAllowedEntities);
    }

    /**
     * 检查字符串是否存在于数组中
     *
     * @param s 要检查的字符串
     * @param array 字符串数组
     * @return 如果字符串存在于数组中返回true，否则返回false
     */
    private static boolean inArray(final String s, final String[] array) {
        for (String item : array) {
            if (item != null && item.equals(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查标签名是否被允许
     *
     * @param name 标签名
     * @return 如果标签被允许返回true，否则返回false
     */
    private boolean allowed(final String name) {
        return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
    }

    /**
     * 检查给定标签的属性是否被允许
     *
     * @param name 标签名
     * @param paramName 属性名
     * @return 如果属性被允许返回true，否则返回false
     */
    private boolean allowedAttribute(final String name, final String paramName) {
        return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
    }
}
